package com.mmp.main.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.common.util.Common;
import com.mmp.main.entity.Hospital;
import com.mmp.main.entity.Site;
import com.mmp.main.util.WebUtil;

public class ChooseSessionHospitalDisplayServlet extends BasicServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		if (!WebUtil.userHasRightToChangeSessionHospital(request)) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}

		int siteId = WebUtil.getParamValueAsInteger(request, "siteId", 0);
		if (siteId != 0) { // if ajax request
			PrintWriter out = response.getWriter();
			try {
				out.print(getHospitalListAsJSONArray(dbQueryManager.getSiteLocations(siteId)));
			} catch (JSONException e) {
				Common.log(e);
			}
			return;
		}

		List<Site> siteList;
		if (WebUtil.currentUserIsDirectorateAdmin(request))
			siteList = dbQueryManager.findAll(Site.class);
		else {
			siteList = new ArrayList<Site>();
			siteList.add(getSessionUser(request).getSite());
		}

		request.setAttribute("siteList", siteList);
		forwardToBasicTemplate(request, response, "ChooseHospital.jsp");

	}

	private JSONArray getHospitalListAsJSONArray(List<Hospital> hospList) throws JSONException {
		JSONArray jsonArray = new JSONArray();
		for (Hospital hosp : hospList) {
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("id", hosp.getId());
			jsonObj.put("name", hosp.getName());
			jsonArray.put(jsonObj);
		}
		return jsonArray;
	}
}
